﻿using System;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections.ObjectModel;

namespace mvcForum.Tests.WebUI {

	[TestFixture]
	public class M020_Paging {
		private IWebDriver driver;
		private String forumName;

		#region Initialization and cleanup
		[TestFixtureSetUp]
		public void TestInitialize() {
			driver = TestHelper.GetDriver();

			forumName = Guid.NewGuid().ToString();

			driver.LogOn(Constants.Users.Admin.Email, Constants.Users.Admin.Password);
			driver.CreateForum("Test board", "Category 1", forumName, "", 1);
			driver.SetStandardAccess("Test board", "Category 1", forumName);
			driver.DisableAntiSpam();
			driver.LogOff();
		}

		[TestFixtureTearDown]
		public void TestCleanup() {
			if (driver != null) {
				driver.Close();
			}
		}
		#endregion

		[Test]
		public void PagingTest() {
			Int32 topicsPerPage = 5;
			driver.LogOn(Constants.Users.Admin.Email, Constants.Users.Admin.Password);
			driver.VisitURL("forumadmin/settings");
			driver.InsertText("TopicsPerPage", topicsPerPage.ToString());
			driver.FindButton("Update").Click();
			driver.LogOff();

			driver.LogOn(Constants.Users.Regular.Email, Constants.Users.Regular.Password);
			for (Int32 index = 1; index <= topicsPerPage; index++) {
				driver.CreateTopic(forumName, String.Format("Topic {0}", index), "bla bla");
			}
			driver.LogOff();

			driver.GoToForum(forumName);
			ReadOnlyCollection<IWebElement> results = driver.FindElements(By.ClassName("pagination"));
			Assert.True(results[0].Text.Contains(String.Format("{0} topics", topicsPerPage)));
			Assert.IsEmpty(results[0].FindElements(By.XPath(".//a")));

			driver.LogOn(Constants.Users.Regular.Email, Constants.Users.Regular.Password);
			driver.CreateTopic(forumName, String.Format("Topic {0}", topicsPerPage + 1), "bla bla");
			driver.LogOff();

			driver.GoToForum(forumName);
			results = driver.FindElements(By.ClassName("pagination"));
			Assert.True(results[0].Text.Contains(String.Format("{0} topics", topicsPerPage + 1)));
			Assert.IsNotEmpty(results[0].FindElements(By.XPath(".//a")));

			driver.LogOn(Constants.Users.Regular.Email, Constants.Users.Regular.Password);
			for (Int32 index = topicsPerPage + 2; index <= 2 * topicsPerPage + 1; index++) {
				driver.CreateTopic(forumName, String.Format("Topic {0}", index ), "bla bla");
			}
			driver.LogOff();

			driver.GoToForum(forumName);
			results = driver.FindElements(By.ClassName("pagination"));
			Assert.True(results[0].Text.Contains(String.Format("{0} topics",  2 * topicsPerPage + 1)), "wrong number of topics");
			// +1 because the actual page is not a link!!
			Assert.AreEqual(results[0].FindElements(By.XPath(".//a")).Count + 1, (Int32)Math.Ceiling((decimal)(2 * topicsPerPage + 1) / topicsPerPage));
		}
	}
}